package cn.exrick.xboot.modules.app.controller;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.enums.QrCodeEnmu;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SpringContextUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.config.redis.RedisRepository;
import cn.exrick.xboot.modules.base.dao.UserDao;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.UserService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author    : LiYuanzhuo
 * description: App扫描二维码登录
 * create time: 2019/9/6 9:11
 */
@Slf4j
@RestController
@RequestMapping(value = "/qrcode")
public class ScanCodeLoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisRepository redisRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    /**
     * @author    : LiYuanzhuo
     * description: app扫码，确认二维码失效与否
     * create time: 2019/9/6 9:56
     */
    @RequestMapping(value = "/scanService",method = RequestMethod.POST)
    public Result<Object> scanService(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        //APP扫描到的内容信息
        String uuid = jsonObject.containsKey("uuid")?jsonObject.getString("uuid"):"";
        String token = jsonObject.containsKey("token")?jsonObject.getString("token"):"";
        String v = stringRedisTemplate.opsForValue().get(SecurityConstant.APP_TOKEN_PRE + token);
        if (v == null || v == ""){
            return new ResultUtil<>().setErrorMsg(401,"登录已失效，请重新登录!");
        }
        log.info("app扫码,传回的参数：uuid{},token{}",uuid ,token);
        //获取uuid，校验redis中是否存在该标识
       // String uuid = message.replace(CommonConstant.APP_QRCODE_FLAG, "");
        String key = CommonConstant.APP_QRCODE_FLAG + uuid;
        log.info("key值" + key);
        if (!redisRepository.exists(key)){
            //如果不存在该KEY，表示二维码已经失效
            log.error("验证码已经失效,请刷新验证码");
            return new ResultUtil<>().setErrorMsg("验证码已经失效,请刷新验证码");
        }else {
            redisTemplate = (RedisTemplate) SpringContextUtil.getBean("redisTemplate");
            RedisSerializer stringSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringSerializer);
            redisTemplate.setValueSerializer(stringSerializer);
            //更新二维码，并将二维码唯一标识与token绑定，有效时间60S
            redisTemplate.opsForValue().set(CommonConstant.APP_QRCODE_STATE + uuid,QrCodeEnmu.scan.toString(),60,TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(CommonConstant.APP_TOKEN_UUID + token,uuid,60,TimeUnit.SECONDS);

            return new ResultUtil<>().setSuccessMsg("二维码有效");
        }

    }

    /**
     * @author    : LiYuanzhuo
     * description: app扫码确认登录
     * create time: 2019/9/6 9:56
     */
    @RequestMapping(value = "/scanLogin",method = RequestMethod.POST)
    public Result<Object> scanLogin(@RequestBody JSONObject jsonObject){
        String token = jsonObject.containsKey("token")?jsonObject.getString("token"):"";
        String username = jsonObject.containsKey("username")?jsonObject.getString("username"):"";
        log.info("app扫码登录第二步，接受的参数：token{},username{}", token ,username);

        //获取用户信息
        User user = userService.findByUsername(username);
        if (user == null) {
            user = userService.findByMobile(username);
            if (user == null){
                return new ResultUtil<Object>().setErrorMsg("用户不存在");
            }
            List<User> userList= userDao.findByMobile(username);
            if (userList.size()>1){
                return new ResultUtil<Object>().setErrorMsg("该手机号绑定了多个账户，请使用身份证号登录！");
            }

        }

        username = user.getUsername();
        log.info("获取到的用户名为：" + username);

        if (user.getStatus().equals(CommonConstant.USER_STATUS_LOCK)){
            return new ResultUtil<Object>().setErrorMsg("该用户已经被禁用！请联系管理员！");
        }

        if( "".equals(token) || "".equals(username)){
            log.error("app确认登录接收的token,username" + token +  ";" + username);
            return new ResultUtil<>().setErrorMsg("传输的数据格式有错误！");
        }
        //根据token获取绑定的uuid，并校验是否已失效
        if (!redisRepository.exists(CommonConstant.APP_TOKEN_UUID + token)){
            log.error("获取信息失败,没成功绑定token与uuid");
            return new ResultUtil<>().setErrorMsg("获取信息失败");
        }

        String uuid = redisRepository.get(CommonConstant.APP_TOKEN_UUID + token);

        redisTemplate = (RedisTemplate) SpringContextUtil.getBean("redisTemplate");
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        //更新二维码状态，并附上用户信息
        redisTemplate.opsForValue().set(CommonConstant.APP_QRCODE_STATE + uuid,"login", 60,TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(CommonConstant.APP_QRCODE_FLAG + uuid,username,120,TimeUnit.SECONDS);
        //删除绑定了的token与uuid
        redisRepository.del(CommonConstant.APP_TOKEN_UUID + token);
        return new ResultUtil<>().setSuccessMsg("确认登陆成功");

    }

}
